package com.chagee.store.operation.server.config;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.chagee.store.operation.common.enums.EmailTypeEnum;
import com.chagee.store.operation.server.model.bo.EmailConfigItem;
import com.chagee.store.operation.server.model.bo.EmailReceiverConfigItem;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author : hk
 * @Date : 2024/12/24
 */


@Configuration
@RefreshScope
@Component
@Slf4j
@ConfigurationProperties(prefix = "email")
public class EmailConfig {

	private List<EmailConfigItem> config;


	public EmailConfigItem select(EmailTypeEnum type) {
		for (EmailConfigItem item : config) {
			if (item.supports(type.name())) {
				EmailConfigItem emailConfigItem = new EmailConfigItem();
				BeanUtils.copyProperties(item, emailConfigItem);
				return emailConfigItem;
			}
		}
		return null;
	}


	public List<EmailConfigItem> getConfig() {
		return config;
	}

	public void setConfig(List<EmailConfigItem> config) {
		this.config = config;
	}

	/**
	 * 获取收邮件人配置
	 * @param receiverConfig config
	 * @return map
	 */
	public EmailReceiverConfigItem getReceiver(String receiverConfig){
		if (StrUtil.isNotEmpty(receiverConfig)) {
			return JSON.parseObject(receiverConfig, new TypeReference<EmailReceiverConfigItem>() {
			});
		}else {
			return new EmailReceiverConfigItem();
		}
	}

	/**
	 * 获取收邮件人配置
	 * @param type enum
	 * @return map
	 */
	public EmailReceiverConfigItem getReceiver(EmailTypeEnum type){
		EmailConfigItem configItem = select(type);
		String receiverConfig = configItem.getReceiverConfig();
		if (StrUtil.isNotEmpty(receiverConfig)) {
			return JSON.parseObject(receiverConfig, new TypeReference<EmailReceiverConfigItem>() {
			});
		}else {
			return new EmailReceiverConfigItem();
		}
	}
}
